package com.manager.container.controller;

import com.manager.common.customer.utils.RemoteExecute;
import com.manager.common.ssh.RemoteExecuteLinuxCommandTools;
import com.manager.common.utils.DataTools;
import com.manager.common.utils.LargeFileHttpUploadUtils;
import com.manager.common.utils.ObjectUtils;
import com.manager.common.vo.PageVO;
import com.manager.common.vo.ResultVO;
import com.manager.container.service.DockerImagesService;
import com.manager.model.DockerImages;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/images")
public class DockerImagesController {

    @Autowired
    private DockerImagesService dockerImagesService;

    @RequestMapping("/getImagePage")
    public PageVO getImagePage(DockerImages model) {
        return dockerImagesService.getImagePage(model);
    }

    @RequestMapping("/addOrUpdate")
    public ResultVO addOrUpdate(DockerImages model) {
        try{
            if(StringUtils.isEmpty(model.getId())){
                dockerImagesService.addImages(model);
            }else {
                dockerImagesService.updateImages(model);
            }
            return ResultVO.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/delete")
    public ResultVO delete(DockerImages model) {
        try{
           dockerImagesService.deleteImages(model);
            return ResultVO.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    @RequestMapping("/getImageList")
    public ResultVO getImageList(DockerImages model) {
        try{
            List<DockerImages> list = dockerImagesService.getImageList(model);
            return ResultVO.success(ObjectUtils.getJSONArray(DockerImages.config,list));
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }
    /**
     linux.server.sftp.ip
     linux.server.sftp.port
     linux.server.sftp.user.name
     linux.server.sftp.password
     linux.server.sftp.image.temp.path
     * */
    @RequestMapping("/pushImages")
    public ResultVO pushImages(DockerImages model) {
        try{
            DockerImages dockerImages = dockerImagesService.getImage(model);
            if("2".equals(dockerImages.getImageType())){
                return localImageFilePush(dockerImages);
            }
            String command1 = "docker login " + dockerImages.getWarehouseAddress() + " -u "
                    + dockerImages.getLoginUserName() + " -p " + dockerImages.getLoginPassword();
            String command2 = " docker pull " + dockerImages.getWarehouseAddress() + "/" + dockerImages.getName() + ":" + dockerImages.getTag();
            ResultVO resultVO = RemoteExecute.executeSsh(command1, command2);
            if(!resultVO.hasSuccess()){
                return ResultVO.failed();
            }
            return ResultVO.success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.failed();
    }

    private ResultVO localImageFilePush(DockerImages dockerImages) throws Exception{
        if(dockerImages == null || StringUtils.isEmpty(dockerImages.getFilePath())){
            return ResultVO.failed("没有找到对应镜像文件");
        }
        String filePath = LargeFileHttpUploadUtils.getBasePath() + dockerImages.getFilePath();
        File file = new File(filePath);
        if(!file.exists()){
            return ResultVO.failed("没有找到对应镜像文件");
        }
        String remoteFile = dockerImages.getName() + "." + dockerImages.getTag() + ".tar";
        String tempPath = DataTools.getSystemSettingStringValByKey("linux.server.sftp.image.temp.path");
        List<String> out = new ArrayList<>();
        RemoteExecuteLinuxCommandTools.uploadFileBySFTP(tempPath,remoteFile,filePath,out);
        out.forEach(v -> {
            System.out.println(v);
        });
        out.clear();
        String command =   "docker import " + tempPath + "/" + remoteFile +" " + dockerImages.getName() + ":" + dockerImages.getTag();
        ResultVO<Object[]> resultVO = RemoteExecute.executeSsh(command);
        if(resultVO.getCode() != 1){
            return ResultVO.failed("导入镜像失败");
        }
        Object[] data =  resultVO.getData();
        String imageId =String.valueOf(data[0]).split(":")[1].substring(0,12);
        dockerImages.setImageId(imageId);
        dockerImagesService.updateImageId(dockerImages);
        return ResultVO.success();
    }
}
